import React, {useEffect, useState} from 'react';
import {NavLink, useHistory} from "react-router-dom";
import axios from "axios";
import LoadingSpinner from "./LoadingSpinner";


export default function Navbar() {
    const [loading, setLoading] = useState(true);
    const [categories, setCategories] = useState([])
    const [keyword, setKeyword] = useState('')
    const history = useHistory()

    useEffect(() => {
        axios.get('/api/v1/categories/')
            .then(response => {
                setLoading(false)
                setCategories(response.data)
            })
            .catch(err => {
                setLoading(false)
                // 如果后端出错，显示为空即可，这里不处理错误
                setCategories([])
            })
    }, [])

    const handleSubmit = e => {
        e.preventDefault()
        if (keyword.length > 0)
            history.push(`/search?keyword=${keyword}`)
    }

    const categoryList = (
        categories.map(category => (
            <li className="nav-item" key={category.name}>
                <NavLink className="nav-link text-capitalize" to={`/category/${category.name}`}>
                    {category.name}
                </NavLink>
            </li>
        ))
    )

    if (loading) return <LoadingSpinner/>

    return (
        <nav className="navbar navbar-expand-lg navbar-light shadow-sm">
            <div className="container">

                <button className="navbar-toggler" type="button" data-bs-toggle="collapse"
                        data-bs-target="#navbarNav">
                    <span className="navbar-toggler-icon"></span>
                </button>

                <div className="collapse navbar-collapse" id="navbarNav">
                    <NavLink className="navbar-brand font-weight-bolder" to='/'>
                        XXX博客
                    </NavLink>


                    <ul className="navbar-nav me-auto">
                        {categoryList}
                    </ul>
                    <form className="d-flex ms-auto" onSubmit={handleSubmit}>
                        <input
                            className="form-control me-2"
                            type="search"
                            placeholder="搜索文章"
                            name="keyword"
                            onChange={e => setKeyword(e.target.value)}
                        />
                    </form>
                </div>
            </div>
        </nav>
    );
};

